<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Mycommon
{

    private $_CI;

    public function __construct()
    {
        $this->_CI = & get_instance();
    }

    public function loadMail()
    {
        $this->_CI->config->load('email');
        $config = $this->_CI->config->item('mail');
        $this->_CI->load->library('PHPMailer/phpmailer');
        $this->_CI->phpmailer->IsSMTP();
        $this->_CI->phpmailer->SMTPAuth = true;
        $this->_CI->phpmailer->SMTPSecure = $config['SMTPSecure'];
        $this->_CI->phpmailer->Host = $config['host'];
        $this->_CI->phpmailer->Port = $config['port'];
        $this->_CI->phpmailer->Username = $config['username'];
        $this->_CI->phpmailer->Password = $config['password'];
        $this->_CI->phpmailer->SetFrom($config['username'], $config['contentFrom']);
        $this->_CI->phpmailer->CharSet = $config['charset'];
    }
    

    function isUrl($input)
    {
        return preg_match("/^[A-Za-z]+:\/\/[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=#]+$/", $input);
    }   

    public function authAdmin()
    {
        if (!$this->_CI->session->userdata('user_id') || !$this->_CI->session->userdata('username') || !$this->_CI->session->userdata('permission')) {
            $back = site_url($this->_CI->uri->uri_string());
            $backlink = urlencode($back);
            redirect('admin/login' . '?back=' . $backlink);
        }
    }
    

    function rangeWeek($datestr)
    {
        date_default_timezone_set(date_default_timezone_get());
        $dt = strtotime($datestr);
        $res['start'] = date('N', $dt) == 1 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('last monday', $dt));
        $res['end'] = date('N', $dt) == 7 ? date('Y-m-d', $dt) : date('Y-m-d', strtotime('next sunday', $dt));
        return $res;
    }
    
    public function getIsAjaxRequest()
	{
		return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
	}
					
	function snippetwop($text,$length=64,$tail="...") {
	    $text = trim($text);
	    $txtl = strlen($text);
	    if($txtl > $length) {
	        for($i=1;$text[$length-$i]!=" ";$i++) {
	            if($i == $length) {
	                return substr($text,0,$length) . $tail;
	            }
	        }
	        for(;$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
	        $text = substr($text,0,$length-$i+1) . $tail;
	    }
	    return $text;
	}
	
	function debug($value, $label = null) {
	    $label = get_tracelog(debug_backtrace(), $label);
	    echo getdebug($value, $label);
	    exit();
	}
	
	function getdebug($value, $label = null) {
	    $value = htmlentities(print_r($value, true));
	    return "<pre>$label$value</pre>";
	}	
	  
}

?>
